package com.oedtech.esl.filter;

import com.oedtech.esl.utils.VerifyUtil;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码检验过滤器
 * @Author QiuLongYu
 * @Date 2019/4/24
 */
@Component
public class ValidateCodeFilter  extends OncePerRequestFilter{


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if ("/login/form".equals(request.getRequestURI()) && "post".equalsIgnoreCase(request.getMethod())) {

            String kaptchaCode = (String) request.getSession().getAttribute(VerifyUtil.VERIFY_KEY);
            String theCode = request.getParameter("verifyCode");
            if (theCode == null || !theCode.equalsIgnoreCase(kaptchaCode)) {
                System.out.println("验证码错误");
                request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,new RuntimeException("验证码错误"));
                response.sendRedirect("/login?error");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
